@extends('layouts.app')

@section('title', '账本管理')

@push('styles')
    <style>
        /* 账本管理页面样式 */
        .account-books-container {
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
            padding-bottom: 100px;
        }

        .create-book-section {
            margin-bottom: 30px;
        }

        .create-book-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .create-book-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .tabs-container {
            margin-bottom: 20px;
        }

        .tabs {
            display: flex;
            background: #f7fafc;
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 20px;
        }

        .tab {
            flex: 1;
            padding: 12px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            color: #718096;
        }

        .tab.active {
            background: white;
            color: #667eea;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .books-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .book-item {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            position: relative;
            cursor: pointer;
        }

        .book-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .book-item.current {
            border: 2px solid #667eea;
            background: linear-gradient(135deg, #f0f4ff 0%, #e8f2ff 100%);
        }

        .book-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .book-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .book-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
        }

        .book-details {
            flex: 1;
        }

        .book-name {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin: 0 0 4px 0;
        }

        .book-stats {
            font-size: 12px;
            display: flex;
            gap: 15px;
        }

        .expense-amount {
            color: #e53e3e;
            font-weight: 500;
        }

        .income-amount {
            color: #38a169;
            font-weight: 500;
        }

        .book-status {
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-current {
            background: #667eea;
            color: white;
        }

        .status-normal {
            background: #f7fafc;
            color: #718096;
        }

        .book-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: none;
            background: #f7fafc;
            color: #718096;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .action-btn:hover {
            background: #edf2f7;
            color: #4a5568;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #4a5568;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .btn-outline {
            background: white;
            border: 1px solid #e2e8f0;
            color: #4a5568;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-outline:hover {
            border-color: #667eea;
            color: #667eea;
        }

        /* 操作菜单样式 */
        .action-menu {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-radius: 20px 20px 0 0;
            box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15);
            transform: translateY(100%);
            transition: transform 0.3s ease;
            z-index: 1050;
        }

        .action-menu.active {
            transform: translateY(0);
        }

        .action-menu-header {
            padding: 20px 24px 10px;
            border-bottom: 1px solid #e2e8f0;
            text-align: center;
            position: relative;
        }

        .action-menu-title {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin: 0;
        }

        .action-menu-close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            font-size: 20px;
            color: #718096;
            cursor: pointer;
        }

        .action-menu-body {
            padding: 10px 0 30px;
        }

        .action-menu-item {
            display: flex;
            align-items: center;
            padding: 16px 24px;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .action-menu-item:hover {
            background: #f7fafc;
        }

        .action-menu-icon {
            width: 24px;
            height: 24px;
            margin-right: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .action-menu-text {
            font-size: 16px;
            color: #2d3748;
        }

        .action-menu-item.danger .action-menu-icon,
        .action-menu-item.danger .action-menu-text {
            color: #e53e3e;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #718096;
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .empty-text {
            font-size: 16px;
            margin-bottom: 8px;
        }

        .empty-hint {
            font-size: 14px;
            color: #a0aec0;
        }

        .modal-test {
            top: 300px;
        }
    </style>

@endpush

@section('main-content')

<!-- 页面头部 -->
<div class="page-header">
    <button class="back-btn" onclick="window.location.href = '{{ route('user.profile') }}'">‹</button>
    <h1 class="page-title">账本管理</h1>
</div>

<!-- 主要内容 -->
<div class="account-books-container">
    <!-- 创建账本按钮 -->
    <div class="create-book-section">
        <button class="create-book-btn" id="create-book-btn">
            <span style="font-size: 20px;">+</span>
            创建新账本
        </button>
    </div>

    <!-- 标签页切换 -->
    <div class="tabs-container">
        <div class="tabs">
            <div class="tab active" data-tab="created">我创建的</div>
            <div class="tab" data-tab="joined">我加入的</div>
        </div>
    </div>

    <!-- 账本列表 -->
    <div class="books-list" id="books-list">
        <!-- 动态加载账本列表 -->
    </div>

    <!-- 空状态 -->
    <div class="empty-state" id="empty-state" style="display: none;">
        <div class="empty-icon">📚</div>
        <div class="empty-text">暂无账本</div>
        <div class="empty-hint">点击上方按钮创建您的第一个账本</div>
    </div>
</div>
@endsection

@section('modal-content')
<!-- 创建账本弹窗 -->
<div class="modal fade" id="createBookModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title">创建新账本</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="create-book-form">
                    <div class="form-group">
                        <label class="form-label">账本名称</label>
                        <input type="text" class="form-input" id="book-name" placeholder="请输入账本名称" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">账本描述</label>
                        <input type="text" class="form-input" id="book-description" placeholder="请输入账本描述（可选）">
                    </div>

                    <div class="form-group">
                        <label class="form-label">选择图标</label>
                        <input type="text" class="form-input" id="emoji-search" placeholder="输入中文搜索图标...">
                        <div class="emoji-selector" id="emoji-selector">
                        </div>
                        <div class="emoji-option-no-results" style="display: none" id="emoji-selector-empty">-- 没有找到匹配的emoji --</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-create-book">创建账本</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑账本弹窗 -->
<div class="modal fade" id="editBookModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title">编辑账本</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="edit-book-form">
                    <div class="form-group">
                        <label class="form-label">账本名称</label>
                        <input type="text" class="form-input" id="edit-book-name" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">账本描述</label>
                        <input type="text" class="form-input" id="edit-book-description">
                    </div>
                    <div class="form-group">
                        <label class="form-label">选择图标</label>
                        <input type="text" class="form-input" id="emoji-search-edit" placeholder="输入中文搜索图标...">
                        <div class="emoji-selector" id="emoji-selector-edit">
                        </div>
                        <div class="emoji-option-no-results" style="display: none" id="emoji-selector-empty-edit">-- 没有找到匹配的emoji --</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-edit-book">保存修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 邀请用户弹窗 -->
<div class="modal fade" id="inviteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">邀请用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="invite-link-section" id="invite-link-section" style="display: none;">
                    <div class="form-group">
                        <label class="form-label">邀请链接</label>
                        <div class="input-group">
                            <input type="text" class="form-input" id="invite-link" readonly>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary" id="copy-link">复制</button>
                    <div class="invite-info">
                        <p class="expires-text" id="expires-text" style="font-size: 14px; color: #718096; margin-top: 10px;"></p>
                    </div>
                </div>

                <div class="generate-section" id="generate-section">
                    <button type="button" class="btn btn-primary" id="generate-invite" style="width: 100%; padding: 15px;">生成邀请链接</button>
                </div>

                <div style="margin-top: 20px; padding: 15px; background: #f7fafc; border-radius: 8px; font-size: 14px; color: #718096;">
                    💡 生成邀请链接后，将链接发送给朋友，对方点击链接即可加入账本。
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 用户管理弹窗 -->
<div class="modal fade" id="membersModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">用户管理</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="members-list">
                    <!-- 动态加载成员列表 -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 账本操作菜单 -->
<div class="action-menu" id="action-menu">
    <div class="action-menu-header">
        <h5 class="action-menu-title" id="action-menu-title">账本操作</h5>
        <button class="action-menu-close" onclick="hideBookActions()">✕</button>
    </div>
    <div class="action-menu-body" id="action-menu-body">
        <!-- 动态生成操作菜单 -->
    </div>
</div>

@endsection

@push('scripts')
<script src="{{ asset('js/emoji-search.js') }}"></script>
<script>
let currentTab = 'created';
let currentBookId = null;
let selectedIcon = '📘';
let allBooks = [];

$(document).ready(function() {
    loadBooks();

    // 标签页切换
    $('.tab').on('click', function() {
        const tab = $(this).data('tab');
        $('.tab').removeClass('active');
        $(this).addClass('active');
        currentTab = tab;
        renderBooks();
    });

    // 创建账本按钮
    $('#create-book-btn').on('click', function() {
        selectedIcon = '📘';
        initEmojiSearch('#emoji-search', '#emoji-selector', '#emoji-selector-empty', selectedIcon);
        $('#createBookModal').modal('show');
    });

    // 确认创建账本
    $('#confirm-create-book').on('click', function() {
        createBook();
    });

    // 确认编辑账本
    $('#confirm-edit-book').on('click', function() {
        updateBook();
    });

    // 生成邀请链接
    $('#generate-invite').on('click', function() {
        generateInviteLink();
    });

    // 复制邀请链接
    $('#copy-link').on('click', function() {
        copyInviteLink();
    });

    // 关闭操作菜单
    $('#overlay').on('click', function() {
        hideBookActions();
    });
});

// 加载账本列表
function loadBooks() {
    $.ajax({
        url: '{{ route("user.books.data") }}',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                allBooks = response.books;
                renderBooks();
            } else {
                showError('加载账本列表失败');
            }
        },
        error: function() {
            showError('加载账本列表失败');
        }
    });
}

// 渲染账本列表
function renderBooks() {
    const filteredBooks = allBooks.filter(book => {
        if (currentTab === 'created') {
            return book.role === 'owner';
        } else {
            return book.role !== 'owner';
        }
    });

    const booksList = $('#books-list');
    const emptyState = $('#empty-state');

    if (filteredBooks.length === 0) {
        booksList.hide();
        emptyState.show();
        return;
    }

    booksList.show();
    emptyState.hide();

    let html = '';
    filteredBooks.forEach(book => {
        const isDefault = book.is_default;
        const statusClass = isDefault ? 'status-current' : 'status-normal';
        const statusText = isDefault ? '当前使用' : '未使用';
        const itemClass = isDefault ? 'book-item current' : 'book-item';

        html += `
            <div class="${itemClass}" data-book-id="${book.id}">
                <div class="book-header">
                    <div class="book-info">
                        <div class="book-icon">${book.icon}</div>
                        <div class="book-details">
                            <h3 class="book-name">${book.name}</h3>
                            <div class="book-stats">
                                <span class="expense-amount">-¥${book.monthly_expense.toFixed(2)}</span>
                                <span class="income-amount">+¥${book.monthly_income.toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                    <div class="book-actions">
                        <span class="book-status ${statusClass}">${statusText}</span>
                        <button class="action-btn" onclick="showBookActions(${book.id}, '${book.name}', '${book.role}')">
                            ⋯
                        </button>
                    </div>
                </div>
            </div>
        `;
    });

    booksList.html(html);
}

// 显示账本操作菜单
function showBookActions(bookId, bookName, role) {
    currentBookId = bookId;
    $('#action-menu-title').text(bookName);

    let menuItems = '';

    if (role === 'owner') {
        // 创建者的操作菜单
        menuItems = `
            <button class="action-menu-item" onclick="editBook()">
                <div class="action-menu-icon">✏️</div>
                <div class="action-menu-text">编辑账本</div>
            </button>
            <button class="action-menu-item" onclick="setDefaultBook()">
                <div class="action-menu-icon">⭐</div>
                <div class="action-menu-text">设为默认</div>
            </button>
            <button class="action-menu-item" onclick="categoryManagement()">
                <div class="action-menu-icon">📂</div>
                <div class="action-menu-text">分类管理</div>
            </button>
            <button class="action-menu-item" onclick="autoTransaction()">
                <div class="action-menu-icon">🔄</div>
                <div class="action-menu-text">定时记账</div>
            </button>
            <button class="action-menu-item" onclick="userManagement()">
                <div class="action-menu-icon">👥</div>
                <div class="action-menu-text">用户管理</div>
            </button>
            <button class="action-menu-item" onclick="inviteUserModal()">
                <div class="action-menu-icon">➕</div>
                <div class="action-menu-text">邀请用户</div>
            </button>
            <button class="action-menu-item danger" onclick="deleteBook()">
                <div class="action-menu-icon">🗑️</div>
                <div class="action-menu-text">删除账本</div>
            </button>
        `;
    } else {
        // 参与者的操作菜单
        menuItems = `
            <button class="action-menu-item" onclick="setDefaultBook()">
                <div class="action-menu-icon">⭐</div>
                <div class="action-menu-text">设为默认</div>
            </button>
            <button class="action-menu-item danger" onclick="leaveBook()">
                <div class="action-menu-icon">🚪</div>
                <div class="action-menu-text">退出账本</div>
            </button>
        `;
    }

    $('#action-menu-body').html(menuItems);
    $('#action-menu').addClass('active');
    $('#overlay').addClass('active');
}

// 隐藏账本操作菜单
function hideBookActions() {
    $('#action-menu').removeClass('active');
    $('#overlay').removeClass('active');
}

// 创建账本
function createBook() {
    const name = $('#book-name').val().trim();
    const description = $('#book-description').val().trim();

    if (!name) {
        showToast('请输入账本名称', 'error');
        return;
    }

    $.ajax({
        url: '{{ route("user.books.store") }}',
        method: 'POST',
        data: {
            name: name,
            description: description,
            icon: selectedIcon,
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.success) {
                $('#createBookModal').modal('hide');
                $('#book-name').val('');
                $('#book-description').val('');
                // $('#emoji-search').val();
                showSuccess('账本创建成功');
                loadBooks();
            } else {
                showError(response.message || '创建失败', response);
            }
        },
        error: function(e) {
            let response = e.responseJSON;
            showError(response.message || '创建失败', response);
        }
    });
}

// 编辑账本
function editBook() {
    const book = allBooks.find(b => b.id === currentBookId);
    if (book) {
        $('#edit-book-name').val(book.name);
        $('#edit-book-description').val(book.description || '');
        selectedIcon = book.icon;
        initEmojiSearch('#emoji-search-edit', '#emoji-selector-edit', '#emoji-selector-empty-edit', selectedIcon);
        $('#editBookModal').modal('show');
    }
    hideBookActions();
}

// 更新账本
function updateBook() {
    const name = $('#edit-book-name').val().trim();
    const description = $('#edit-book-description').val().trim();

    if (!name) {
        showError('请输入账本名称');
        return;
    }

    $.ajax({
        url: `{{ url('/user/books') }}/${currentBookId}`,
        method: 'PUT',
        data: {
            name: name,
            description: description,
            icon: selectedIcon,
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.success) {
                $('#editBookModal').modal('hide');
                showSuccess('账本更新成功');
                loadBooks();
            } else {
                showError(response.message || '更新失败', response);
            }
        },
        error: function(e) {
            showError(e.responseJSON.message || '更新失败，请重试', e.responseJSON);
        }
    });
}

// 设为默认账本
function setDefaultBook() {
    $.ajax({
        url: `{{ url('/user/books') }}/${currentBookId}/set-default`,
        method: 'POST',
        data: {
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.success) {
                showSuccess('默认账本设置成功');
                loadBooks();
            } else {
                showError(response.message || '设置失败', response);
            }
        },
        error: function(e) {
            showError(e.responseJSON.message || '设置失败，请重试', e.responseJSON);
        }
    });
    hideBookActions();
}

// 分类管理
function categoryManagement() {
    window.location.href = `{{ url('/user/books') }}/${currentBookId}/categories`;
}

// 自动记账
function autoTransaction() {
    window.location.href = `{{ url('/auto-transaction') }}?book_id=${currentBookId}`;
    hideBookActions();
}

// 用户管理
function userManagement() {
    loadMembers();
    $('#membersModal').modal('show');
    hideBookActions();
}

// 加载成员列表
function loadMembers() {
    $.ajax({
        url: `{{ url('/user/books') }}/${currentBookId}/members`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                renderMembers(response.members);
            } else {
                showError(response.message || '加载成员列表失败', response);
            }
        },
        error: function(e) {
            showError(e.responseJSON.message || '加载成员列表失败', e.responseJSON);
        }
    });
}

// 渲染成员列表
function renderMembers(members) {
    let html = '';
    members.forEach(member => {
        let roleText = member.role === 'admin' ? '管理员' : '成员';
        if (member.is_creator) {
            roleText = '创建者';
        }

        html += `
            <div style="display: flex; align-items: center; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #e2e8f0;">
                <div>
                    <div style="font-weight: 500;">${member.name}</div>
                    <div style="font-size: 12px; color: #718096;">${member.phone || '未绑定手机'}</div>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="padding: 4px 8px; background: #f7fafc; border-radius: 4px; font-size: 12px;width: 100%;">${roleText}</span>
                    ${!member.is_creator ? '<button class="btn btn-danger" style="padding: 4px 8px; font-size: 12px;" onclick="removeMember(' + member.id + ')">移除</button>' : ''}
                </div>
            </div>
        `;
    });

    $('#members-list').html(html);
}

// 邀请用户弹窗
function inviteUserModal() {
    // 重置弹窗状态
    $('#invite-link-section').hide();
    $('#generate-section').show();
    $('#invite-link').val('');
    $('#expires-text').text('');

    $('#inviteModal').modal('show');
    hideBookActions();
}

// 生成邀请链接
function generateInviteLink() {
    const button = $('#generate-invite');
    button.prop('disabled', true).text('生成中...');

    $.ajax({
        url: `{{ url('/user/books') }}/${currentBookId}/invite`,
        method: 'POST',
        data: {
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            if (response.success) {
                $('#invite-link').val(response.invite_url);
                // 格式化过期时间显示
                const expiresAt = new Date(response.expires_at);
                const now = new Date();
                const diffHours = Math.ceil((expiresAt - now) / (1000 * 60 * 60));

                let expiresText;
                if (diffHours <= 0) {
                    expiresText = '链接已过期';
                } else if (diffHours <= 24) {
                    expiresText = `链接将于 ${diffHours} 小时后过期 (${response.expires_at})`;
                } else {
                    const diffDays = Math.ceil(diffHours / 24);
                    expiresText = `链接将于 ${diffDays} 天后过期 (${response.expires_at})`;
                }

                $('#expires-text').text(expiresText);
                $('#generate-section').hide();
                $('#invite-link-section').show();
                showSuccess('邀请链接生成成功');
            } else {
                showError(response.message || '生成失败', response);
            }
        },
        error: function(e) {
            showError(e.responseJSON.message || '生成失败，请重试', e.responseJSON);
        },
        complete: function() {
            button.prop('disabled', false).text('生成邀请链接');
        }
    });
}

// 复制邀请链接
function copyInviteLink() {
    const linkInput = $('#invite-link')[0];
    linkInput.select();
    linkInput.setSelectionRange(0, 99999); // 移动端兼容

    try {
        document.execCommand('copy');
        showSuccess('邀请链接已复制到剪贴板');
    } catch (err) {
        showError('复制失败，请手动复制链接');
    }
}

// 删除账本
function deleteBook() {
    if (confirm('确定要删除这个账本吗？删除后无法恢复。')) {
        $.ajax({
            url: `{{ url('/user/books') }}/${currentBookId}`,
            method: 'DELETE',
            data: {
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('账本删除成功');
                    loadBooks();
                } else {
                    showError(response.message || '删除失败', response);
                }
            },
            error: function(e) {
                showError(e.responseJSON.message || '删除失败', e.responseJSON);
            }
        });
    }
    hideBookActions();
}

// 离开账本
function leaveBook() {
    if (confirm('确定要离开这个账本吗？')) {
        $.ajax({
            url: `{{ url('/user/books') }}/${currentBookId}/leave`,
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('已成功离开账本');
                    loadBooks();
                } else {
                    showError(response.message || '离开失败', response);
                }
            },
            error: function(e) {
                showError(e.responseJSON.message || '离开失败，请重试', e.responseJSON);
            }
        });
    }
    hideBookActions();
}

// 移除成员
function removeMember(userId) {
    if (confirm('确定要移除该成员吗？')) {
        $.ajax({
            url: `{{ url('/user/books') }}/${currentBookId}/members/${userId}`,
            type: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('成员移除成功');
                    // 重新加载成员列表
                    loadMembers();
                } else {
                    showError(response.message || '移除失败', response);
                }
            },
            error: function(e) {
                showError(e.responseJSON.message || '离开失败，请重试', e.responseJSON);
            }
        });
    }
}

</script>
@endpush
